package com.knife.tools;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;

import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FilenameUtils;

public class FileUpload extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String uploadPath = ""; // 上传目录
    private String sitePath = ""; // 站点目录
    private String tmpPath = ""; // 临时目录
    private File tempPath; // 用于存放临时文件的目录
    private String filext="";

    @SuppressWarnings("unchecked")
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        tempPath = new File(tmpPath);
        res.setContentType("text/html; charset=UTF-8");
        int fn = Parameter.dealInt(req.getParameter("CKEditorFuncNum"));
        //int sid = Parameter.dealInt(req.getParameter("sid"));
        sitePath = "/upload/images/";
        //uploadPath = "upload" + File.separator + "images";
        PrintWriter out = res.getWriter();
        // System.out.println(req.getContentLength());
        // System.out.println(req.getContentType());
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        // 允许设置内存中存储数据的门限，单位：字节
        factory.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        // 如果文件大小大于SizeThreshold，则保存到临时目录
        factory.setRepository(new File(tmpPath));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        // 最大上传大小，默认20M，单位：字节
        upload.setSizeMax(20480000);
        try {
            List fileItems = upload.parseRequest(req);
            // assume we know there are two files. The first file is a small
            // text file, the second is unknown and is written to a file on
            // the server
            Iterator iter = fileItems.iterator();

            // 正则匹配，过滤路径取文件名
            String regExp = ".+\\\\(.+)$";

            // 过滤掉的文件类型
            String[] errorType = {".exe", ".com", ".cgi", ".asp", ".jsp"};
            Pattern p = Pattern.compile(regExp);
            String itemNo = "";// 文件存放路径
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                // 忽略其他不是文件域的所有表单信息
                if (!item.isFormField()) {
                    String name = item.getName();
                    long size = item.getSize();
                    if ((name == null || name.equals("")) && size == 0) {
                        continue;
                    }
                        //判断文件类型
                        for (int temp = 0; temp < errorType.length; temp++) {
                            if (name.endsWith(errorType[temp])) {
                                throw new IOException(name + ": 错误的文件类型");
                            }
                        }
                        filext = FilenameUtils.getExtension(name);
    					if(filext.trim().length()<=0){
    						if(name.lastIndexOf(".")>0){
    							filext=name.substring(name.lastIndexOf(".")+1,name.length());
    						}
    					}
    					UUID uid = UUID.randomUUID();
    					String newfilename = uid.toString() + "." + filext.toLowerCase();
                        
                        java.util.Date mydate = new java.util.Date();
                        java.text.SimpleDateFormat dformat = new java.text.SimpleDateFormat(
                                "yyyyMMdd");
                        String dateDir = dformat.format(mydate);
                        String savepath = uploadPath + File.separator + dateDir + File.separator
                                + newfilename;
                        try {
                            // 保存上传的文件到指定的目录
                            if (!new File(uploadPath + File.separator + dateDir).isDirectory()) {
                                new File(uploadPath + File.separator + dateDir).mkdir();
                            }
                            item.write(new File(savepath));

                            //将上传的文件发送到CMS的传输队列
							/*TurboCMS.deploy.DeployTask objDep = new TurboCMS.deploy.DeployTask();
                            java.util.Vector rsDep=new java.util.Vector();
                            rsDep = objDep.Search("'" + savepath.replaceAll("'", "''") + "' LIKE directory || '%'");
                            System.out.println("总共" + rsDep.size() + "个文件将加入到队列,文件路径是:" + savepath);
                            for(int j=0;j<rsDep.size();j++){
                            objDep = (TurboCMS.deploy.DeployTask)rsDep.get(j);
                            System.out.println("文件：" + savepath + "已加入队列;");
                            objDep.AddFileToUpdate(savepath);
                            }*/

                            out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('"
                                    + fn
                                    + "','"
                                    + sitePath
                                    + dateDir
                                    + "/"
                                    + newfilename
                                    + "','');</script>");
                        } catch (Exception e) {
                            out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','','上传失败," + e.getMessage() + "');</script>");
                        }
                }
            }
        } catch (IOException e) {
        	e.printStackTrace();
            //out.println(e);
            out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','" + e.getMessage() + "','上传失败" + e.getMessage() + "');</script>");
        } catch (FileUploadException e) {
        	e.printStackTrace();
            //out.println(e);
            out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','" + e.getMessage() + "','上传失败" + e.getMessage() + "');</script>");
        }
    }

    @Override
    public void init() throws ServletException {
        this.tmpPath = Config.TempPath;
        this.tmpPath += File.separator;
        this.uploadPath = Config.SiteDirectory + File.separator+"upload"+File.separator+"images";
        //到web.xml中的配置文件用于保存上传文件，也可以在已开始定义的时候初始化，不过这样可以通过改动配置文件来改动存放路径，不用该代码，增加了灵活性。
    }
}